package com.example.bbs.interceptor;

import com.example.bbs.domain.entity.User;
import com.example.bbs.service.impl.NoticeService;
import com.example.bbs.service.impl.PostServiceImpl;
import com.example.bbs.util.HostHold;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ReturnInterceptor implements HandlerInterceptor {


    @Autowired
    private NoticeService noticeService;

    @Autowired
    private PostServiceImpl postServiceImpl;


    @Value("${gitee.client.id}")
    private String clientId;

    @Value("${gitee.redirect.uri}")
    private String redirectUri;


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = HostHold.get();
        if (modelAndView != null) {
            modelAndView.addObject("hourHotPostRank", postServiceImpl.getHourHotPostRank());
            modelAndView.addObject("clientId", clientId);
            modelAndView.addObject("redirectUri", redirectUri);
            if (user != null) {
                modelAndView.addObject("loginUser", user);
                modelAndView.addObject("noticeCount", noticeService.getUnReadNoticeCount());
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除资源
        HostHold.clear();
        SecurityContextHolder.clearContext();
    }
}
